using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;

namespace MediaBackup
{
    [StructLayout(LayoutKind.Sequential)]
    public struct NetResource
    {
        public int nScope;
        public int nType;
        public int nDisplayType;
        public int nUsage;
        public string strLocalName;
        public string strRemoteName;
        public string strComment;
        public string strProvider;
    }

    public static class WNet
    {
        [DllImport("mpr.dll", CharSet = CharSet.Ansi)]
        public static extern uint WNetAddConnection2(ref NetResource netResource, string strPassword, string strUsername, uint nFlag);

        public static void AddConnection(string localName, string remoteName, string username, string password)
        {
            NetResource netResource = new NetResource();
            netResource.nType = 1; //RESOURCETYPE_DISK   
            netResource.strLocalName = localName;
            netResource.strRemoteName = remoteName;
            netResource.strProvider = null;

            uint nRet = WNetAddConnection2(ref netResource, username, password, 0);
            if (nRet != 0)
                throw new COMException(string.Format("WNetAddConnection2 failed: {0}", nRet), (int)nRet);
        }

        public static void Authenticate(string path, string username, string password)
        {
            if (path.StartsWith(@"\\") && username != null)
            {
                try
                {
                    string server = path.Substring(0, path.IndexOf('\\', 2));
                    WNet.AddConnection("", server, username, password);
                }
                catch (COMException e)
                {
                    Log.Write(e);
                }
            }
        }
    }
}
